package map.android.baidu.carpool.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;

import com.baidu.components.api.extra.APIProxy;

public class NetworkUtils {
	public static boolean isNetworkConnected() {
		return checkNetworkStatus(false);
	}

	public static boolean checkNetworkStatus(boolean showToast) {
		Context context = APIProxy.res().getBaseActivity();
		if (context == null) {
			return false;
		}

		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		final NetworkInfo network = cm.getActiveNetworkInfo();
		boolean connected = false;
		if (network != null) {
			connected = network.isConnected() || network.isAvailable();
		} else {
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			State wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
			connected = wifiManager.isWifiEnabled() && wifiState.equals(State.CONNECTED);
		}
		if (!connected) {
			if (showToast) {
				ToastForCarpool.show(context, "抱歉，您的网络不通，请检查网络后重试");
			}
			return false;
		}
		return true;
	}
}
